
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import { routeMenuList} from '/@/router'
interface RouteMenu {
  key: string,
  title: string
  icon?: string,
  children?: Array<RouteMenu> | undefined,
  parentKeys?: Array<string>
}
interface MenuState {
  menuList: Array<RouteMenu>
}
export const useMenuStore = defineStore('app-menu', {
  // 推荐使用 完整类型推断的箭头函数
  state: (): MenuState => {
    return {
      menuList: []
    }
  },
  actions: {
    /**
     * 递归路由配置，转成菜单
     * @param routes 
     * @param parentKeys
     * @returns 
     */
    _routeToMenu(routes: Array<any>,parentKeys: Array<string>) {
      const userStore = useUserStore()
      const menuList:Array<RouteMenu> = []
      routes.filter(item=>{
        // 过滤掉隐藏的菜单
        return item.meta?.hideMenu !== true
      }).filter(item=>{
        return userStore.hasPerm(item.meta?.perm)
      }).sort((a,b)=>{
        // 对菜单进行排序
        return (a.meta?.orderNo || 99)-(b.meta?.orderNo || 99)
      }).forEach((item: any)=>{
        const childParentKeys: Array<string> = []
        childParentKeys.push(...parentKeys)
        childParentKeys.push(item.name)
        const children = this._routeToMenu(item.children || [],childParentKeys)
        menuList.push({
          key: item.name,
          title: item.meta?.title,
          icon: item.meta?.icon,
          children: children.length ? children: undefined,
          parentKeys
        })
      })
      return menuList
    },
    /**
     * 通过key获取菜单项数据-递归
     * @param key 
     * @param datas 
     * @returns 
     */
    _getMenu(key: string,datas: Array<RouteMenu>): RouteMenu | undefined {
      let node: RouteMenu | undefined
      datas.forEach((item: RouteMenu)=>{
        if(item.key == key) {
          node = item
        } else {
          if(!node) {
            node = this._getMenu(key,item.children || [])
          }
        }
      })
      return node
    },
    /**
     * 通过key获取菜单项数据
     * @param key 
     * @returns 
     */
    getMenu(key: string):RouteMenu | undefined {
      return this._getMenu(key,this.menuList)
    },
    initMenu() {
      this.menuList = this._routeToMenu(routeMenuList,[])
    }
  },
  getters: {
   menus():Array<RouteMenu> {
    return this.menuList
   }
  },
  persist: {
    storage: localStorage,
    key: "app-menu"
  }
})